# enemy_manager.gd
extends Node

# ======================================================
# 敌人管理器 v2.0
# 根据新权重系统管理敌人生成
# ======================================================

#region 配置常量
# ------------------------------------------------------
const BASE_ENEMY_COUNT := 10
const ENEMY_PER_LEVEL := 1
const ELITE_SPAWN_PERCENT := [0.0, 0.1, 0.15, 0.2, 0.25, 0.3] # 各房间精英概率（索引0占位）
#endregion


#region 核心逻辑
# ------------------------------------------------------
func generate_enemies(current_level: int, room_number: int) -> Dictionary:
	"""
	生成敌人数量字典（新版结构）
	@return: 结构示例
	{
		"normal": {"common_soldier":3, "assault_trooper":2},
		"elite": {"elite_guardian":1},
		"boss": {"mech_tyrant":1}  # 仅当房间6时存在
	}
	"""
	var result := {
		"normal": {},
		"elite": {},
		"boss": {}
	}
	var total = BASE_ENEMY_COUNT + (current_level * 6 + room_number - 7) * ENEMY_PER_LEVEL
	
	if room_number == 6:
		var boss_key = _generate_boss(current_level)
		result["boss"][boss_key] = 1
		total -= 5
	print(total)
	var elite_num = roundi(total * ELITE_SPAWN_PERCENT[room_number - 1])
	if elite_num < 0:
		elite_num = 0
	var normal_num = total - elite_num
	if normal_num < 0:
		normal_num = 0

	# 生成普通敌人
	for _i in range(normal_num):
		var key = _select_enemy_key(current_level, false)
		result["normal"][key] = result["normal"].get(key, 0) + 1

	# 生成精英敌人
	for _i in range(elite_num):
		var key = _select_enemy_key(current_level, true)
		result["elite"][key] = result["elite"].get(key, 0) + 1
	
	return result

func generate_level_data(level: int) -> void:
	"""
	生成完整关卡数据（包含6个房间）
	@param level: 当前关卡数（≥1）
	"""
	var level_data := []
	
	# 生成1-5号房间数据
	for room in range(1, 7):
		var room_data = generate_enemies(level, room)
		level_data.append(room_data)
	GameData.level_data.room_queue = level_data
	

func _generate_boss(current_level: int) -> String:
	var boss_keys = GameData.boss_enemies.keys()
	var weights := []
	
	for key in boss_keys:
		var boss = GameData.boss_enemies[key]
		weights.append(max(boss.base_weight + boss.level_weight * current_level, 0))
	
	return boss_keys[GameManager.rng.rand_weighted(weights)]
	

func _select_enemy_key(level: int, is_elite: bool) -> String:
	var candidates = GameData.normal_enemies
	if is_elite and not GameData.elite_enemies.is_empty():
		candidates = GameData.elite_enemies
	
	var keys = candidates.keys()
	var weights := []
	
	for key in keys:
		var enemy = candidates[key]
		weights.append(max(enemy.base_weight + enemy.level_weight * level, 0))
	
	# 权重全为0时随机选择
	if weights.reduce(func(a, b): return a + b, 0) == 0:
		return keys[GameManager.rng.randi() % keys.size()]
	
	return keys[GameManager.rng.rand_weighted(weights)]

func instantiate_enemy(data: Dictionary) -> Node:
	var scene = load(data.scene_path)
	if not scene:
		push_error("无法加载敌人场景: " + data.scene_path)
		return _create_fallback_enemy()
	
	var instance = scene.instantiate()
	
	return instance

func _create_fallback_enemy() -> Node:
	var node = Node.new()
	node.set_script(load("res://enemies/base_enemy.gd"))
	return node
#endregion
